package cn.core.sign.service.impl;

import cn.core.sign.eo.Org;
import cn.core.sign.eo.Post;
import cn.core.sign.mapper.OrgMapper;
import cn.core.sign.mapper.PostMapper;
import cn.core.sign.mapper.PostStaffMapper;
import cn.core.sign.qo.OrgQO;
import cn.core.sign.qo.PostQO;
import cn.core.sign.service.intf.IOrgService;
import cn.core.sign.vo.OrgVO;
import cn.core.sign.vo.StaffPostNexusVO;
import cn.core.tool.event.CoreDataEvent;
import cn.core.tool.exception.CoreException;
import cn.core.tool.util.CoreTool;
import cn.core.tool.util.CoreTree;
import cn.core.tool.util.Paging;
import cn.core.tool.util.Param;
import com.google.gson.reflect.TypeToken;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;

/**
 * 组织机构 服务实现
 */
@Log4j2
@Primary
@Service
public class OrgServiceImpl implements IOrgService {

  @Resource
  private OrgMapper orgMapper;

  @Resource
  private ApplicationEventPublisher applicationEventPublisher;

  @Resource
  private PostMapper postMapper;

  @Resource
  private PostStaffMapper postStaffMapper;

  @Override
  @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)
  public Org save(Org eo) throws Exception {
    try {
      if (CoreTool.isNullEo(eo)) {
        throw new CoreException(CoreException.E_PARAM_ERR);
      }
      eo.setId(CoreTool.getUUID32());
      if (CoreTool.isNotNullStr(eo.getPid())) {
        eo.setIdPath(orgMapper.pk(new OrgQO().setId(eo.getPid())).getIdPath() + "/" + eo.getId());
      } else {
        eo.setIdPath(eo.getId());
      }
      orgMapper.save(eo);
      return eo;
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.error(e.getMessage(), e);
      }
      throw e;
    }
  }

  @Override
  @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)
  public Collection<Org> saveBatch(Collection<Org> eos) throws Exception {
    try {
      if (CoreTool.isEmpty(eos)) {
        throw new CoreException(CoreException.E_PARAM_ERR);
      }
      for (Org eo : eos) {
        if (CoreTool.isNullEo(eo)) {
          throw new CoreException(CoreException.E_PARAM_ERR);
        }
        eo.setId(CoreTool.getUUID32());
      }
      orgMapper.saveBatch(new Paging<>(), eos);
      return eos;
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.error(e.getMessage(), e);
      }
      throw e;
    }
  }

  @Override
  @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)
  public Org update(Org eo) throws Exception {
    try {
      if (CoreTool.isNullEo(eo) || CoreTool.isNullStr(eo.getId())) {
        throw new CoreException(CoreException.E_PARAM_ERR);
      }
      Org oeo = orgMapper.pk(new OrgQO().setId(eo.getId()));
      if (CoreTool.isNullEo(oeo)) {
        throw new CoreException(CoreException.E_PARAM_ERR);
      }
//      if (eo.getVersions() != null ? !eo.getVersions().equals(oeo.getVersions()) : oeo.getVersions() != null ? true : false) {
//        throw new CoreException(CoreException.E_VERSIONS_ERR);
//      }
      orgMapper.update(eo);
      return eo;
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.error(e.getMessage(), e);
      }
      throw e;
    }
  }

  @Override
  @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)
  public Collection<Org> updateBatch(Collection<Org> eos) throws Exception {
    try {
      if (CoreTool.isEmpty(eos)) {
        throw new CoreException(CoreException.E_PARAM_ERR);
      }
      for (Org eo : eos) {
        if (CoreTool.isNullEo(eo) || CoreTool.isNullStr(eo.getId())) {
          throw new CoreException(CoreException.E_PARAM_ERR);
        }
        Org oeo = orgMapper.pk(new OrgQO().setId(eo.getId()));
        if (CoreTool.isNullEo(oeo)) {
          throw new CoreException(CoreException.E_PARAM_ERR);
        }
//        if (eo.getVersions() != null ? !eo.getVersions().equals(oeo.getVersions()) : oeo.getVersions() != null ? true : false) {
//          throw new CoreException(CoreException.E_VERSIONS_ERR);
//        }
      }
      orgMapper.updateBatch(new Paging<>(), eos);
      return eos;
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.error(e.getMessage(), e);
      }
      throw e;
    }
  }

  @Override
  @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)
  public void remove(Org eo) throws Exception {
    try {
      if (CoreTool.isNullEo(eo) || CoreTool.isNullStr(eo.getId())) {
        throw new CoreException(CoreException.E_PARAM_ERR);
      }
      Collection<Org> rOrgSet = orgMapper.query(new OrgQO().setPid(eo.getId()));
      if (CoreTool.isNotEmpty(rOrgSet)) {
        throw new CoreException("此组织机构拥有子级，删除失败！");
      }
      Collection<Post> rPostSet = postMapper.query(new PostQO().setFkid(eo.getId()));
      if (CoreTool.isNotEmpty(rPostSet)) {
        throw new CoreException("此组织机构拥有岗位，删除失败！");
      }
      orgMapper.remove(eo);
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.error(e.getMessage(), e);
      }
      throw e;
    }
  }

  @Override
  @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)
  public void removeBatch(Collection<Org> eos) throws Exception {
    try {
      if (CoreTool.isEmpty(eos)) {
        throw new CoreException(CoreException.E_PARAM_ERR);
      }
      for (Org eo : eos) {
        if (CoreTool.isNullEo(eo) || CoreTool.isNullStr(eo.getId())) {
          throw new CoreException(CoreException.E_PARAM_ERR);
        }
      }
      orgMapper.removeBatch(eos);
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.error(e.getMessage(), e);
      }
      throw e;
    }
  }

  @Override
  public Long count(OrgQO qo) throws Exception {
    try {
      return orgMapper.count(qo);
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.error(e.getMessage(), e);
      }
      throw e;
    }
  }

  @Override
  public Org pk(OrgQO qo) throws Exception {
    try {
      if (CoreTool.isNullEo(qo) || CoreTool.isNullStr(qo.getId())) {
        throw new CoreException(CoreException.E_PARAM_ERR);
      }
      return orgMapper.pk(qo);
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.error(e.getMessage(), e);
      }
      throw e;
    }
  }

  @Override
  public Collection<Org> query(OrgQO qo) throws Exception {
    try {
      return orgMapper.query(qo);
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.error(e.getMessage(), e);
      }
      throw e;
    }
  }

  @Override
  public Paging<Org> paging(Param<OrgQO> param) throws Exception {
    try {
      if (CoreTool.isNullEo(param)) {
        throw new CoreException(CoreException.E_PARAM_ERR);
      }
      if (param.getPage() < 1 || param.getRows() < 1) {
        throw new CoreException(CoreException.E_PAGING_PARAM_ERR);
      }
      Paging<Org> paging = new Paging<>(param);
      if (CoreTool.isEmpty(param.getData()) || CoreTool.isNullEo(param.get())) {
        Long count = orgMapper.count(null);
        paging.setCount(count);
        if (count > 0) {
          if (count <= paging.getOffset()) {
            throw new CoreException(CoreException.E_PAGING_PARAM_ERR);
          }
          paging.setData(orgMapper.paging(paging, null));
        }
      } else {
        Long count = orgMapper.count(param.get());
        paging.setCount(count);
        if (count > 0) {
          if (count <= paging.getOffset()) {
            throw new CoreException(CoreException.E_PAGING_PARAM_ERR);
          }
          paging.setData(orgMapper.paging(paging, param.get()));
        }
      }
      return paging;
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.error(e.getMessage(), e);
      }
      throw e;
    }
  }

  @Override
  public Long countVo(OrgQO qo) throws Exception {
    try {
      return orgMapper.countVo(qo);
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.error(e.getMessage(), e);
      }
      throw e;
    }
  }

  @Override
  public OrgVO pkVo(OrgQO qo) throws Exception {
    try {
      if (CoreTool.isNullEo(qo) || CoreTool.isNullStr(qo.getId())) {
        throw new CoreException(CoreException.E_PARAM_ERR);
      }
      return orgMapper.pkVo(qo);
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.error(e.getMessage(), e);
      }
      throw e;
    }
  }

  @Override
  public Collection<OrgVO> queryVo(OrgQO qo) throws Exception {
    try {
      return orgMapper.queryVo(qo);
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.error(e.getMessage(), e);
      }
      throw e;
    }
  }

  @Override
  public Paging<OrgVO> pagingVo(Param<OrgQO> param) throws Exception {
    try {
      if (CoreTool.isNullEo(param)) {
        throw new CoreException(CoreException.E_PARAM_ERR);
      }
      if (param.getPage() < 1 || param.getRows() < 1) {
        throw new CoreException(CoreException.E_PAGING_PARAM_ERR);
      }
      Paging<OrgVO> paging = new Paging<>(param);
      if (CoreTool.isEmpty(param.getData()) || CoreTool.isNullEo(param.get())) {
        Long count = orgMapper.countVo(null);
        paging.setCount(count);
        if (count > 0) {
          if (count <= paging.getOffset()) {
            throw new CoreException(CoreException.E_PAGING_PARAM_ERR);
          }
          paging.setData(orgMapper.pagingVo(paging, null));
        }
      } else {
        Long count = orgMapper.countVo(param.get());
        paging.setCount(count);
        if (count > 0) {
          if (count <= paging.getOffset()) {
            throw new CoreException(CoreException.E_PAGING_PARAM_ERR);
          }
          paging.setData(orgMapper.pagingVo(paging, param.get()));
        }
      }
      return paging;
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.error(e.getMessage(), e);
      }
      throw e;
    }
  }

  @Override
  public CoreTree<?> getOrgTreeData(OrgQO qo) throws Exception {
    try {
      CoreTree<?> tree = null;
      Collection<CoreTree<?>> treeSet = new ArrayList<>();
      Collection<Org> rOrgSet = orgMapper.query(qo);
      if (CoreTool.isNotEmpty(rOrgSet)) {
        CoreDataEvent coreDataEvent = new CoreDataEvent("getDictValueMapInfoByDictKey", "orgType");
        applicationEventPublisher.publishEvent(coreDataEvent);
        LinkedHashMap<String, String> dictValueMapInfo = CoreTool.isNotNullStr(coreDataEvent.getData()) ? coreDataEvent.getData(new TypeToken<LinkedHashMap<String, String>>(){}) : new LinkedHashMap<String, String>();
        for (Org eo : rOrgSet) {
          treeSet.add(new CoreTree<Org>(eo)
              .setId(eo.getId())
              .setKey(eo.getId())
              .setName(eo.getOrgName())
              .setTkey(eo.getOrgType())
              .setTitle(eo.getOrgNameAbbr() + " - [" + dictValueMapInfo.get(eo.getOrgType()) + "]")
              .setValue(eo.getId())
              .setPid(eo.getPid()));
        }
      }
      tree = CoreTool.toTree(treeSet, true);
      return tree;
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.error(e.getMessage(), e);
      }
      throw e;
    }
  }

  @Override
  public CoreTree<?> getOrgPostTreeData(OrgQO qo) throws Exception {
    try {
      CoreTree<?> tree = null;
      Collection<CoreTree<?>> treeSet = new ArrayList<>();
      Collection<Org> rOrgSet = orgMapper.query(qo);
      if (CoreTool.isNotEmpty(rOrgSet)) {
        CoreDataEvent coreDataEvent = new CoreDataEvent("getDictValueMapInfoByDictKey", "orgType");
        applicationEventPublisher.publishEvent(coreDataEvent);
        LinkedHashMap<String, String> dictValueMapInfo = CoreTool.isNotNullStr(coreDataEvent.getData()) ? coreDataEvent.getData(new TypeToken<LinkedHashMap<String, String>>(){}) : new LinkedHashMap<String, String>();
        for (Org eo : rOrgSet) {
          treeSet.add(new CoreTree<Org>(eo, false, false, false, true)
              .setId(eo.getId())
              .setKey(eo.getId())
              .setName(eo.getOrgName())
              .setTkey(eo.getOrgType())
              .setTitle(eo.getOrgNameAbbr() + " - [" + dictValueMapInfo.get(eo.getOrgType()) + "]")
              .setValue(eo.getId())
              .setPid(eo.getPid()));
        }
      }
      Collection<Post> rPostSet = postMapper.query(new PostQO().setWeightOrderAsc(CoreTool.isNotNullEo(qo) ? qo.getWeightOrderAsc() : null));
      if (CoreTool.isNotEmpty(rPostSet)) {
        for (Post eo : rPostSet) {
          treeSet.add(new CoreTree<Post>(eo)
              .setId(eo.getId())
              .setKey(eo.getId())
              .setName(eo.getPostName())
              .setTkey("post")
              .setTitle(eo.getPostName() + " - [岗位]")
              .setValue(eo.getId())
              .setPid(eo.getFkid()));
        }
      }
      tree = CoreTool.toTree(treeSet, true);
      return tree;
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.error(e.getMessage(), e);
      }
      throw e;
    }
  }

  @Override
  public CoreTree<?> getOrgPostStaffTreeData(OrgQO qo) throws Exception {
    try {
      CoreTree<?> tree = null;
      Collection<CoreTree<?>> treeSet = new ArrayList<>();
      Collection<Org> rOrgSet = orgMapper.query(qo);
      if (CoreTool.isNotEmpty(rOrgSet)) {
        CoreDataEvent coreDataEvent = new CoreDataEvent("getDictValueMapInfoByDictKey", "orgType");
        applicationEventPublisher.publishEvent(coreDataEvent);
        LinkedHashMap<String, String> dictValueMapInfo = CoreTool.isNotNullStr(coreDataEvent.getData()) ? coreDataEvent.getData(new TypeToken<LinkedHashMap<String, String>>(){}) : new LinkedHashMap<String, String>();
        for (Org eo : rOrgSet) {
          treeSet.add(new CoreTree<Org>(eo, false, false, false, true)
              .setId(eo.getId())
              .setKey(eo.getId())
              .setName(eo.getOrgName())
              .setTkey(eo.getOrgType())
              .setTitle(eo.getOrgNameAbbr() + " - [" + dictValueMapInfo.get(eo.getOrgType()) + "]")
              .setValue(eo.getId())
              .setPid(eo.getPid()));
        }
      }
      Collection<Post> rPostSet = postMapper.query(new PostQO().setWeightOrderAsc(CoreTool.isNotNullEo(qo) ? qo.getWeightOrderAsc() : null));
      if (CoreTool.isNotEmpty(rPostSet)) {
        for (Post eo : rPostSet) {
          treeSet.add(new CoreTree<Post>(eo, false, false, false, true)
              .setId(eo.getId())
              .setKey(eo.getId())
              .setName(eo.getPostName())
              .setTkey("post")
              .setTitle(eo.getPostName() + " - [岗位]")
              .setValue(eo.getId())
              .setPid(eo.getFkid()));
        }
      }
      Collection<StaffPostNexusVO> rStaffPostNexusVOSet = postStaffMapper.getStaffPostNexus(CoreTool.isNotNullEo(qo) ? qo.getWeightOrderAsc() : null);
      if (CoreTool.isNotEmpty(rStaffPostNexusVOSet)) {
        for (StaffPostNexusVO eo : rStaffPostNexusVOSet) {
          treeSet.add(new CoreTree<StaffPostNexusVO>(eo)
              .setId(eo.getId())
              .setKey(eo.getId())
              .setName(eo.getStaffName())
              .setTkey("staff")
              .setTitle(eo.getStaffName() + "(工号:" + eo.getStaffNo() + ") - [员工]")
              .setValue(eo.getId())
              .setPid(eo.getPostId()));
        }
      }
      tree = CoreTool.toTree(treeSet, true);
      return tree;
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.error(e.getMessage(), e);
      }
      throw e;
    }
  }

}
